package com.frxuexi.park2209.visitor

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.VisitorBean
import com.frxuexi.base.mvvm.BaseActivity
import com.frxuexi.base.net.Const
import com.frxuexi.park2209.R
import com.frxuexi.park2209.adapter.VisitorAdapter
import com.frxuexi.park2209.databinding.ActivityVisitorBinding
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class VisitorActivity : BaseActivity<ActivityVisitorBinding,VisitorViewModel>() {
    lateinit var visitorAdapter: VisitorAdapter
    override fun initData() {
        lifecycleScope.launch {
            vm.visitorSuc.collect{
                if(it.isNotEmpty()){
                    val vistiorBean = Gson().fromJson(it, VisitorBean::class.java)
                    visitorAdapter.apply {
                        addData(vistiorBean)
                        notifyDataSetChanged()
                    }
                    Log.i("===",it)
                }
            }
        }

        lifecycleScope.launch {
            vm.delVisitorSuc.collect{
                if(it.isNotEmpty()){
                    ToastUtils.showLong(it)
                    visitorAdapter.data.clear()
                    vm.getVisitors(mapOf("userId" to 0))
                }
            }
        }
    }

    override fun initView() {
        binding.headerVisitor.headerAdd.apply {
            visibility=View.VISIBLE
            setOnClickListener {
                startActivity(Intent(this@VisitorActivity,AddVisitorActivity::class.java))
            }
        }

        binding.headerVisitor.ivBack.setOnClickListener {
            finish()
        }

        visitorAdapter= VisitorAdapter()
        binding.rvVisitor.apply {
            adapter=visitorAdapter
            layoutManager=LinearLayoutManager(this@VisitorActivity)
        }

        visitorAdapter.setOnItemLongClickListener { adapter, view, position ->
            vm.delVisitor(mapOf("visitorId" to visitorAdapter.data.get(position).visitorId))
            return@setOnItemLongClickListener true
        }

    }

    override fun onResume() {
        super.onResume()
        visitorAdapter.data.clear()
        vm.getVisitors(mapOf("userId" to 0))
    }
}